﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="bootstrap.min.css" rel="stylesheet">
</head>
<body class="container py-4">

    <!-- 上传并嵌入水印 -->
    <div class="card mb-4">
        <div class="card-body">
            <h5 class="card-title">嵌入水印</h5>
            <form action="api/Watermark/uploadAndEmbed"
                  method="post"
                  enctype="multipart/form-data"
                  onsubmit="return handleUpload(event)">
                <div class="mb-3">
                    <input type="file" name="file" class="form-control" required>
                </div>
                <div class="mb-3 row align-items-center">
                    <!-- 新增 row 和 align-items-center -->
                    <div class="col-sm-3">
                        <!-- 标签列 -->
                        <label for="watermarkInput" class="form-label mb-0">水印文字</label>
                    </div>
                    <div class="col-sm-9">
                        <!-- 输入框列 -->
                        <input type="text"
                               name="watermarkTxt"
                               id="watermarkInput"
                               value=""
                               class="form-control"
                               placeholder="输入水印文字"
                               required>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary">上传并嵌入水印</button>
            </form>
            <div id="result" class="mt-3"></div>
        </div>
    </div>

    <!-- 提取水印 -->
    <div class="card">
        <div class="card-body">
            <h5 class="card-title">提取水印</h5>
            <form id="extractForm">
                <div class="mb-3">
                    <input type="file" id="extractFile" class="form-control" required>
                </div>
                <button type="button"
                        class="btn btn-info"
                        onclick="extractWatermark()">
                    提取水印
                </button>
            </form>
            <div id="extractResult" class="mt-3"></div>
        </div>
    </div>

    <script>
        async function handleUpload(event) {
            event.preventDefault();
            const form = event.target;
            const button = form.querySelector('button[type="submit"]');
            const originalBtnText = button.innerHTML;
            const resultDiv = document.getElementById('result');

            try {
                // 显示加载状态
                button.innerHTML = `
                <span class="spinner-border spinner-border-sm"></span> 处理中...
            `;
                button.disabled = true;

                // 构造请求
                const formData = new FormData(form);

                const response = await fetch(form.action, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`请求失败: ${response.status}`);
                }

                // 获取调试信息
                const debugInfo = response.headers.get('X-Debug-Info');
                if (debugInfo) {
                    console.log('调试信息:', JSON.parse(debugInfo));

                    var info = JSON.parse(debugInfo);
                    // 显示调试信息
                    resultDiv.innerHTML = `
                <div class="alert alert-success mt-3">
                    <h5>调试信息</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <p>总bit数：${info.TotalBits}</p>
                            <p>错误比特数：${info.ErrorBits}</p>
                            <p>Psnr：${Number(info.Psnr).toFixed(2)}</p>
                            <p>备注：${info.Note}</p>
                        </div>
                    </div>
                </div>
            `;
                } else {
                    resultDiv.innerHTML = "";
                }

                // 处理文件下载
                const blob = await response.blob();
                const filename = getFilenameFromResponse(response);
                triggerFileDownload(blob, filename);

            } catch (error) {
                alert(`操作失败: ${error.message}`);
            } finally {
                // 恢复按钮状态
                button.innerHTML = originalBtnText;
                button.disabled = false;
            }
        }

        // 从响应头获取文件名
        function getFilenameFromResponse(response) {
            const disposition = response.headers.get('Content-Disposition');
            const filenameRegex = /filename\*?=UTF-8''([^;]+)|filename="?([^";]+)"?/i;
            const matches = disposition.match(filenameRegex);
            const encodedName = matches[1] || matches[2];
            return decodeURIComponent(encodedName);
        }

        // 触发文件下载
        function triggerFileDownload(blob, filename) {
            // 修正后的安全文件名处理
            const safeFilename = filename
                .replace(/[/\\?%*:|"<>]/g, '_')  // 替换系统保留字符
                .replace(/\s+/g, '_');          // 空格转下划线

            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = safeFilename;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        }
        // 提取水印功能
        async function extractWatermark() {
            const formData = new FormData()
            formData.append('file', document.getElementById('extractFile').files[0])

            try {
                const response = await fetch('api/Watermark/Extract', {
                    method: 'POST',
                    body: formData
                })

                if (!response.ok) throw new Error('提取失败')
                const data = await response.json()

                document.getElementById('extractResult').innerHTML = `
                    <div class="alert alert-success">
                        提取结果：<strong>${data.result}</strong>
                    </div>
                `
            } catch (error) {
                document.getElementById('extractResult').innerHTML = `
                    <div class="alert alert-danger">${error.message}</div>
                `
            }
        }

    </script>

    <style>
        .card {
            max-width: 600px;
            margin: 0 auto;
        }

        .card-title {
            color: #0d6efd;
        }

        .btn {
            min-width: 120px;
        }
    </style>
</body>
</html>